package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @Author: SerMs
 * @Date: 2023/11/29 10 24
 * @Email: 1839928782@qq.com
 * @Blog: https://serms.top
 **/
@Component
public class RedisWorker {

    //开始时间戳
    private static final long BEGIN_TIMESTAMP = 1672531200L;


    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 业务前缀
     *
     * @param keyPrefix
     * @return
     */
    public long nextId(String keyPrefix) {
        // 生产时间戳
        LocalDateTime now = LocalDateTime.now();
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = epochSecond - BEGIN_TIMESTAMP;
        // 生产序列号
        String format = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + format);
        // 拼接并返回
        long l = timestamp << 32;
        long l1 = l | count;
        return timestamp << 32 | count;
    }

    public static void main(String[] args) {
        // 得到时间
        LocalDateTime time = LocalDateTime.of(2023, 1, 1, 0, 0, 0);
        System.out.println(time);
        // 得到秒数
        long epochSecond = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(epochSecond);
    }
}
